<template>
  <view class="bg-gray-50 min-h-screen w-[750rpx] box-border bgs">
    <!-- Header -->
    <PageHeader title="" :showBack="true" :onlyBack="true" />
    <view
      class="bg-gradient-to-r sticky top-0 z-[2] from-blue-600 to-purple-600 text-white p-[40rpx] text-center relative overflow-hidden"
    >
      <view
        class="absolute w-[300rpx] h-[300rpx] bg-white bg-opacity-10 rounded-full -top-[100rpx] -right-[80rpx]"
      >
      </view>
      <view
        class="absolute w-[200rpx] h-[200rpx] bg-white bg-opacity-8 rounded-full -bottom-[80rpx] -left-[60rpx]"
      >
      </view>

      <text class="text-[42rpx] font-bold mb-[10rpx] block relative z-2"
        >成为平台商家</text
      >
      <text class="text-[26rpx] opacity-90 relative z-2"
        >开启您的商业之旅，共享平台资源</text
      >
    </view>

    <view class="p-[50rpx]">
      <!-- 商家类型选择 -->
      <view
        class="bg-white rounded-[20rpx] p-[30rpx] shadow-lg mb-[50rpx] border border-gray-100"
      >
        <view
          class="text-[32rpx] text-blue-600 mb-[30rpx] pb-[15rpx] border-b-2 border-blue-50 flex items-center"
        >
          <view
            class="w-[50rpx] h-[50rpx] bg-blue-50 rounded-full flex items-center justify-center mr-[15rpx]"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="shangjia"
              size="20"
              color="#4a6bff"
            />
          </view>
          <text>选择商家类型</text>
        </view>

        <view class="flex flex-wrap gap-[30rpx]">
          <view
            v-for="(type, index) in merchantTypes"
            :key="index"
            class="flex-1 min-w-[200rpx] border-2 rounded-[20rpx] p-[30rpx] text-center cursor-pointer transition-all relative overflow-hidden"
            :class="
              selectedType === type.value
                ? 'border-blue-600 bg-blue-50'
                : 'border-gray-200 bg-gray-50'
            "
            @click="selectType(type.value)"
          >
            <view
              v-if="selectedType === type.value"
              class="absolute top-[10rpx] right-[10rpx] w-[30rpx] h-[30rpx] bg-blue-600 text-white rounded-full flex items-center justify-center text-[20rpx]"
            >
              ✓
            </view>
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              :name="type.icon"
              size="30"
              color="#4a6bff"
            />
            <text class="text-[30rpx] font-semibold mb-[10rpx] block">{{
              type.name
            }}</text>
            <text class="text-[24rpx] text-gray-600">{{ type.desc }}</text>
          </view>
        </view>
      </view>

      <!-- 商家信息 -->
      <view
        class="bg-white rounded-[20rpx] p-[30rpx] shadow-lg mb-[50rpx] border border-gray-100"
      >
        <view
          class="text-[32rpx] text-blue-600 mb-[30rpx] pb-[15rpx] border-b-2 border-blue-50 flex items-center"
        >
          <view
            class="w-[50rpx] h-[50rpx] bg-blue-50 rounded-full flex items-center justify-center mr-[15rpx]"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="xinxiinfo21"
              size="20"
              color="#4a6bff"
            />
          </view>
          <text>商家信息</text>
        </view>

        <nut-form ref="formRef" :model="formData">
          <!-- 选择行业 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              选择行业 <text class="text-red-500">*</text>
            </text>
            <view
              class="w-full p-[25rpx] text-[26rpx] border-2 border-gray-200 rounded-[15rpx] bg-gray-50"
              @click="showIndustryPicker = true"
            >
              {{ industryText || "请选择所属行业（可多选）" }}
            </view>

            <nut-popup
              v-model:visible="showIndustryPicker"
              position="bottom"
              round
            >
              <view class="bg-white p-[40rpx] max-h-[70vh] overflow-auto">
                <view class="text-[32rpx] font-bold mb-[30rpx] text-center"
                  >选择行业（可多选）</view
                >

                <view class="space-y-[20rpx]">
                  <view
                    v-for="item in industryOptions"
                    :key="item.value"
                    class="flex items-center p-[20rpx] border-b border-gray-100"
                    @click="toggleIndustry(item.value)"
                  >
                    <nut-checkbox
                      :model-value="selectedIndustries.includes(item.value)"
                      class="mr-[20rpx]"
                    />
                    <text class="text-[28rpx]">{{ item.text }}</text>
                  </view>
                </view>

                <view class="flex justify-center mt-4 w-full">
                  <nut-button
                    type="primary"
                    class="mt-[40rpx]"
                    @click="onIndustryConfirm"
                  >
                    确认选择
                  </nut-button>
                </view>
              </view>
            </nut-popup>
          </view>

          <!-- 服务范围 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              项目介绍 <text class="text-red-500">*</text>
            </text>
            <nut-textarea
              v-model="formData.serviceScope"
              placeholder="请详细描述您的服务范围、服务区域及服务内容"
              class="w-full !p-2 !h-[200rpx] box-border border-solid !border-2 !border-gray-500 !rounded-[12rpx] !bg-gray-50"
              maxlength="500"
            />
          </view>

          <!-- 上传营业执照 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              上传营业执照 <text class="text-red-500">*</text>
            </text>
            <view
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
              :class="
                uploadedLicense
                  ? 'border-blue-600 bg-blue-50'
                  : 'hover:border-blue-600 hover:bg-blue-50'
              "
              v-if="!uploadedLicense"
              @click="uploadLicense"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                :name="uploadedLicense ? 'file-image' : 'tubiao-yunshangchuan'"
                class="text-[50rpx] mb-[20rpx]"
                :class="uploadedLicense ? 'text-green-500' : 'text-blue-600'"
                size="40"
                color="#4a6bff"
              />
              <text class="text-[26rpx] text-gray-600 block">
                {{ uploadedLicense ? "营业执照已上传" : "点击上传营业执照" }}
              </text>
              <text class="text-[22rpx] text-gray-500 mt-[15rpx] block">
                {{
                  uploadedLicense
                    ? "点击可重新上传"
                    : "支持 JPG、PNG 格式，大小不超过 5MB"
                }}
              </text>
            </view>
            <!-- 显示营业执照图片 -->
            <view
              v-else-if="uploadedLicense"
              class="border-2 border-dashed border-gray-200 flex flex-col items-center justify-center rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all hover:border-blue-600 hover:bg-blue-50"
              @click="uploadLicense"
            >
              <img :src="getFullPath(formData.businessPic)" class="max-w-full max-h-[400rpx] rounded-lg mb-[20rpx]" />
              <view class="text-[24rpx] text-blue-600">
                <text class="block mb-[10rpx]">营业执照已上传</text>
                <text class="text-[20rpx] text-blue-400">点击重新上传</text>
              </view>
            </view>
          </view>

           <!-- 上传授权书 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              公司盖章的授权书 <text class="text-red-500">*</text>
              <text class="text-blue-500 cursor-pointer ml-[16rpx]" @tap="showTemplateModal">授权书模版预览</text>
              <text class="text-blue-500 underline cursor-pointer ml-[30rpx]" @tap="downloadTemplateModal">下载</text>

            </text>

            <view
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
              :class="
                uploadedBook
                  ? 'border-blue-600 bg-blue-50'
                  : 'hover:border-blue-600 hover:bg-blue-50'
              "
              v-if="!uploadedBook"
              @click="uploadBook"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                :name="uploadedBook ? 'file-image' : 'tubiao-yunshangchuan'"
                class="text-[50rpx] mb-[20rpx]"
                :class="uploadedBook ? 'text-green-500' : 'text-blue-600'"
                size="40"
                color="#4a6bff"
              />
              <text class="text-[26rpx] text-gray-600 block">
                {{ uploadedBook ? "授权书已上传" : "点击上传授权书" }}
              </text>
              <text class="text-[22rpx] text-gray-500 mt-[15rpx] block">
                {{
                  uploadedBook
                    ? "点击可重新上传"
                    : "支持 JPG、PNG 格式，大小不超过 5MB"
                }}
              </text>
            </view>
            <!-- 显示授权书图片 -->
            <view
              v-else-if="uploadedBook"
              class="border-2 border-dashed border-gray-200 flex flex-col items-center justify-center rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all hover:border-blue-600 hover:bg-blue-50"
              @click="uploadBook"
            >
              <img :src="getFullPath(formData.authorization)" class="max-w-full max-h-[400rpx] rounded-lg mb-[20rpx]" />
              <view class="text-[24rpx] text-blue-600">
                <text class="block mb-[10rpx]">授权书已上传</text>
                <text class="text-[20rpx] text-blue-400">点击重新上传</text>
              </view>
            </view>
          </view>

          <!-- 上传正面身份证 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              上传正面身份证 <text class="text-red-500">*</text>
            </text>
            <view
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
              :class="
                uploadedFrontCard
                  ? 'border-blue-600 bg-blue-50'
                  : 'hover:border-blue-600 hover:bg-blue-50'
              "
              v-if="!uploadedFrontCard"
              @click="uploadIdCard('front')"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                :name="
                  uploadedFrontCard ? 'file-image' : 'shenfenzhengzhengmian'
                "
                class="text-[50rpx] mb-[20rpx]"
                :class="uploadedFrontCard ? 'text-green-500' : 'text-blue-600'"
                size="50"
                color="#4a6bff"
              />
              <text class="text-[26rpx] text-gray-600 block">
                {{
                  uploadedFrontCard
                    ? "身份证人像面已上传"
                    : "点击上传身份证正面"
                }}
              </text>
              <text class="text-[22rpx] text-gray-500 mt-[15rpx] block">
                {{
                  uploadedFrontCard
                    ? "点击可重新上传"
                    : "请确保身份证信息清晰可见"
                }}
              </text>
            </view>
            <!-- 显示身份证图片 -->
            <view
              v-else-if="uploadedFrontCard"
              class="border-2 border-dashed border-gray-200 flex flex-col items-center justify-center rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all hover:border-blue-600 hover:bg-blue-50"
              @click="uploadIdCard('front')"
            >
              <img :src="getFullPath(formData.frontPic)" class="max-w-full max-h-[400rpx] rounded-lg mb-[20rpx]" />
              <view class="text-[24rpx] text-blue-600">
                <text class="block mb-[10rpx]">身份证正面已上传</text>
                <text class="text-[20rpx] text-blue-400">点击重新上传</text>
              </view>
            </view>
          </view>

          <!-- 上传国徽面 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              上传反面身份证 <text class="text-red-500">*</text>
            </text>
            <view
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
              :class="
                uploadedBackCard
                  ? 'border-blue-600 bg-white'
                  : 'hover:border-blue-600 hover:bg-white'
              "
              v-if="!uploadedBackCard"
              @click="uploadIdCard('back')"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                :name="uploadedBackCard ? 'file-image' : 'shenfenzhengfanmian2'"
                class="text-[50rpx] mb-[20rpx]"
                :class="uploadedBackCard ? 'text-green-500' : 'text-blue-600'"
                size="50"
                color="#4a6bff"
              />
              <text class="text-[26rpx] text-gray-600 block">
                {{ uploadedBackCard ? "身份证已上传" : "点击上传身份证反面" }}
              </text>
              <text class="text-[22rpx] text-gray-500 mt-[15rpx] block">
                {{
                  uploadedBackCard
                    ? "点击可重新上传"
                    : "请确保身份证信息清晰可见"
                }}
              </text>
            </view>
            <!-- 显示身份证反面图片 -->
            <view
              v-else-if="uploadedBackCard"
              class="border-2 border-dashed border-gray-200 flex flex-col items-center justify-center rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all hover:border-blue-600 hover:bg-blue-50"
              @click="uploadIdCard('back')"
            >
              <img :src="getFullPath(formData.backPic)" class="max-w-full max-h-[400rpx] rounded-lg mb-[20rpx]" />
              <view class="text-[24rpx] text-blue-600">
                <text class="block mb-[10rpx]">身份证反面已上传</text>
                <text class="text-[20rpx] text-blue-400">点击重新上传</text>
              </view>
            </view>
          </view>

          <!-- 押金说明 -->
          <view class="bg-blue-50 rounded-[15rpx] p-[30rpx] mb-[40rpx]">
            <view class="text-[28rpx] font-semibold mb-[15rpx] text-blue-600">
              <text class="mr-1">🔸</text>
              <text>押金规则说明</text>
            </view>
            <view class="text-[24rpx] leading-[1.8]">
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text
                  >需缴纳平台保证金：<text class="font-bold"
                    >¥{{ depositAmount }}</text
                  ></text
                >
              </view>
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>审核不通过时，押金将在3-5个工作日内原路退回</text>
              </view>
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>合作期间如无违规行为，保证金在退出平台时全额退还</text>
              </view>
              <view class="ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>保证金用于保障平台用户权益和服务质量</text>
              </view>
            </view>
          </view>

          <!-- 会员费说明 -->
          <view class="bg-purple-50 rounded-[15rpx] p-[30rpx] mb-[40rpx]">
            <view class="text-[28rpx] font-semibold mb-[15rpx] text-purple-600">
              <text class="mr-1">🔸</text>
              <text>会员费说明</text>
            </view>
            <view class="text-[24rpx] leading-[1.8]">
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text
                  >成为平台商家需缴纳{{ curDuration  }}会员费：<text class="font-bold text-red-500"
                    >¥{{ vipAmount }}</text
                  ></text
                >
              </view>
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>会员费用于平台技术服务和商家权益保障</text>
              </view>
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>会员期满后需续费才能继续使用商家服务</text>
              </view>
              <view class="ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>会员费一经缴纳不予退还，请知悉</text>
              </view>
            </view>
          </view>
        </nut-form>
      </view>

      <!-- 提交按钮 -->
      <nut-button
        type="primary"
        size="large"
        v-if="formData.is_pay != 1"
        class="w-full text-[32rpx] font-semibold bg-gradient-to-r from-blue-600 to-purple-600 h-[96rpx]"
        @click="handleSubmit(status)"
      >
        {{ status ? "提交" : "提交审核" }}
      </nut-button>
    </view>

    <!-- Footer -->
    <!-- <view class="text-center p-[30rpx] text-gray-500 text-[24rpx]">
      <text>© 2023 平台商家入驻中心 | 客服电话: 400-888-8888</text>
    </view> -->

    <!-- 支付方式选择弹窗 -->
    <PaymentMethodModal 
      v-model="showPaymentModal" 
      :amount="totalPayAmount"
      @confirm="handlePaymentConfirm"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post, getFullPath } from "@/utils/request";
import PageHeader from "@/components/PageHeader.vue";
import PaymentMethodModal from "@/components/PaymentMethodModal.vue";
import { useUserStore } from "@/store/user";
const userStore = useUserStore();
// 使用网络图片作为模版预览
const moban = 'http://www.dzgktf.com/templets/default/images/wtyt.jpg';
// PDF 文件下载链接
const fileUrl = 'https://www.m5.nl9555.com/授权书模板.pdf'

getIndustryText();
getMerchantTypeText();

interface IndustryColumn {
  update_time: null | number;
  create_time: number;
  img_url: null;
  name: string;
  description: string;
  id: number;
  deposit: number;
  membershipFee: number;
}

interface IndustryItem {
  columns: IndustryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface merchantTypes {
  columns: IndustryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

export interface Request {
  // 反面证件
  backPic?: string;
  // 正面证件
  frontPic?: string;
  // id
  id?: number;
  // 行业
  industrys?: string[];
  // 分页查询 第几页
  pageNo?: number;
  // 分页查询 每页多少条
  pageSize?: number;
  // 用户名
  realName?: string;
  // 证件编号
  realNo?: string;
  // 营业执照
  businessPic?: string;
  // 服务范围
  service_scope?: string;
  // 商家类型
  type?: string;
  agreeTerms?: boolean;
  [property: string]: any;
}

// 表单数据
const formData = ref<Request>({});

// 商家类型
const merchantTypes = ref([
  {
    value: "",
    name: "",
    desc: "提供专业服务解决方案",
    icon: "canyin",
    deposit: 2000,
    vipFree: 2000,
  },
  {
    value: "",
    name: "",
    desc: "提供专业培训与指导",
    icon: "peixunguanli",
    deposit: 2000,
    vipFree: 2000,
  },
  {
    value: "",
    name: "",
    desc: "传统文化与技艺传承",
    icon: "a-xintuobeifen2",
    deposit: 2000,
    vipFree: 2000,
  },
  {
    value: "",
    name: "",
    desc: "提供优质产品与货源",
    icon: "gongyingshang",
    deposit: 2000,
    vipFree: 2000,
  },
  {
    value: "",
    name: "",
    desc: "提供优质产品与货源",
    icon: "hezuo",
    deposit: 2000,
    vipFree: 2000,
  },
  {
    value: "",
    name: "",
    desc: "提供优质产品与货源",
    icon: "qiyezizhi",
    deposit: 2000,
    vipFree: 2000,
  },
  {
    value: "",
    name: "",
    desc: "提供优质产品与货源",
    icon: "a-hezuo3",
    deposit: 2000,
    vipFree: 2000,
  }
]);
// 商家类型列表
function getMerchantTypeText() {
  post("/dictionary/merchantType").then((res) => {
    console.log("==>", res.data);
    merchantTypes.value = res.data.map((item: merchantTypes) => ({
      name: item.columns.name,
      value: item.columns.id.toString(),
      deposit: item.columns.deposit,
      vipFree: item.columns.membershipFee,
      duration: (item.columns as any).duration || '1年'
    }));
    console.log("==>", merchantTypes.value);
  });
}

// 选择商家类型
const selectType = (type: string) => {
  console.log(type);
  selectedType.value = type;
  // 保存商家类型
  formData.value.type = type;
};

// 行业相关
const industryOptions = ref<{ text: string; value: number }[]>([]);
// 修改行业选择相关状态
const showIndustryPicker = ref(false);
const selectedIndustries = ref<number[]>([]); // 存储选中的行业ID
const industryText = ref("");


// 授权书模版弹窗状态
const showTemplateModal = () => {
  Taro.previewImage({
    urls: [moban],
  });
}

const downloadTemplateModal = () => {
  // H5 环境下的文件下载
  try {
    // 创建一个隐藏的 a 标签来触发下载
    const link = document.createElement('a');
    link.href = fileUrl;
    link.download = '授权书模板.pdf'; // 设置下载文件名
    link.target = '_blank'; // 在新窗口打开，避免页面跳转
    
    // 将链接添加到页面并触发点击
    document.body.appendChild(link);
    link.click();
    
    // 清理：移除临时创建的链接
    document.body.removeChild(link);
    
    Taro.showToast({
      title: '开始下载授权书模板',
      icon: 'success',
      duration: 2000
    });
  } catch (error) {
    console.error('下载失败:', error);
    Taro.showToast({
      title: '尝试其他方式下载',
      icon: 'error',
      duration: 2000
    });
    Taro.downloadFile({
      url: fileUrl,
    });
  }
}

// 获取行业列表
function getIndustryText() {
  post("/dictionary/industry").then((res) => {
    industryOptions.value = res.data.map((item: IndustryItem) => ({
      text: item.columns.name,
      value: item.columns.id,
    }));
  });
}

// 处理行业选择确认
function onIndustryConfirm() {
  showIndustryPicker.value = false;

  // 生成行业名称文本
  const selectedNames = industryOptions.value
    .filter((item) => selectedIndustries.value.includes(item.value))
    .map((item) => item.text);

  industryText.value = selectedNames.join("、");

  // 保存行业ID数组
  formData.value.industrys = selectedIndustries.value.map(id => id.toString());
}

// 切换行业选择状态
function toggleIndustry(id: number) {
  const index = selectedIndustries.value.indexOf(id);
  if (index > -1) {
    selectedIndustries.value.splice(index, 1);
  } else {
    selectedIndustries.value.push(id);
  }
}
const params = Taro.getCurrentInstance().router?.params;
console.log("==>", params);
// 上传状态
const selectedType = ref(params?.type || '1');
const uploadedLicense = ref(false);
const uploadedFrontCard = ref(false);
const uploadedBackCard = ref(false);
const uploadedBook = ref(false);

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);
const currentPaymentAmount = ref(0);

// 上传营业执照
const uploadLicense = () => {
  Taro.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      console.log(res);
      Taro.showLoading({ title: "上传中..." });
      const uploadRes = await Taro.uploadFile({
        url: getFullPath("/file/upload"),
        filePath: res.tempFilePaths[0],
        name: "file",
        header: {
          token: Taro.getStorageSync("token"),
        },
      });
      Taro.hideLoading();
      const data = JSON.parse(uploadRes.data);
      // 保存url地址
      formData.value.businessPic = data.data;
      uploadedLicense.value = true;
      Taro.showToast({
        title: "营业执照上传成功",
        icon: "success",
      });
    },
  });
};

// 上传授权书
const uploadBook = () => {
  Taro.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      console.log(res);
      Taro.showLoading({ title: "上传中..." });
      const uploadRes = await Taro.uploadFile({
        url: getFullPath("/file/upload"),
        filePath: res.tempFilePaths[0],
        name: "file",
        header: {
          token: Taro.getStorageSync("token"),
        },
      });
      Taro.hideLoading();
      const data = JSON.parse(uploadRes.data);
      // 保存url地址
      formData.value.authorization = data.data;
      uploadedBook.value = true;
      Taro.showToast({
        title: "授权书上传成功",
        icon: "success",
      });
    },
  });
};

// 上传身份证
const uploadIdCard = (pic: string) => {
  // 上传逻辑
  Taro.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      // console.log(res);
      Taro.showLoading({ title: "上传中..." });
      const uploadRes = await Taro.uploadFile({
        url: getFullPath("/file/upload"),
        filePath: res.tempFilePaths[0],
        name: "file",
        header: {
          token: Taro.getStorageSync("token"),
        },
      });
      Taro.hideLoading();
      const data = JSON.parse(uploadRes.data);
      if (pic == "front") {
        // 保存url地址
        formData.value.frontPic = data.data;
        // console.log("正面===>", getFullPath(formData.value.frontPic));
        uploadedFrontCard.value = true;
        Taro.showToast({
          title: "身份证反面上传成功",
          icon: "success",
        });
      } else {
        // 保存url地址
        formData.value.backPic = data.data;
        // console.log("反面===>", getFullPath(formData.value.backPic));
        uploadedBackCard.value = true;
        Taro.showToast({
          title: "身份证反面上传成功",
          icon: "success",
        });
      }
    },
  });
};

// 提交表单
const handleSubmit = async (status: string) => {
  // alert(formData.value.type)
  console.log("status===>", formData.value);
  // if (status) {
  //   Taro.showToast({
  //     title: "正在审核中,请等待!",
  //     icon: "none",
  //   });
  //   return;
  // }
  if(selectedType.value == '') {
    Taro.showToast({
      title: "请选择商家类型",
      icon: "none",
    });
    return;
  }
  if (!formData.value.industrys) {
    Taro.showToast({
      title: "请选择所属行业",
      icon: "none",
    });
    return;
  }

  if (!formData.value.serviceScope) {
    Taro.showToast({
      title: "请填写服务范围",
      icon: "none",
    });
    return;
  }

  if (!uploadedLicense.value) {
    Taro.showToast({
      title: "请上传营业执照",
      icon: "none",
    });
    return;
  }

  if (!uploadedFrontCard.value) {
    Taro.showToast({
      title: "请上传正面身份证",
      icon: "none",
    });
    return;
  }
  if (!uploadedBackCard.value) {
    Taro.showToast({
      title: "请上传反面身份证",
      icon: "none",
    });
    return;
  }
  // API接口 -- 先支付再提交审核
 
  const res = await post("/user/merchantAuthentication", formData.value);
    if (res.code == 0) {
      Taro.showToast({
        title:
          "提交成功！\n您的申请已进入审核流程，我们将在3-5个工作日内完成审核。",
        icon: "success",
        duration: 3000,
      });
      
      // 使用 setTimeout 确保稳定执行
      console.log("userStore.userInfo.deposit ==>", userStore.userInfo.deposit);
      console.log("depositAmount.value ==>", depositAmount.value);
      setTimeout(() => {
        if(depositAmount.value != userStore.userInfo.deposit) {
          // 显示支付方式选择弹窗
          currentPaymentAmount.value = totalPayAmount.value;
          showPaymentModal.value = true;
        }
        else{
          userStore.fetchUserInfo()
          Taro.navigateBack();
        }
      }, 1000);
    }
};

// 押金金额 - 根据当前选中的商户类型动态获取
const depositAmount = computed(() => {
  const currentType = merchantTypes.value.find(type => type.value === selectedType.value);
  return currentType?.deposit || 2000;
});

const vipAmount = computed(() => {
  const currentType = merchantTypes.value.find(type => type.value === selectedType.value);
  return currentType?.vipFree || 2000;
});

const curDuration = computed(() => {
  const currentType = merchantTypes.value.find(type => type.value === selectedType.value);
  return (currentType as any)?.duration || '1年';
});

// 总支付金额
const totalPayAmount = computed(() => {
  return depositAmount.value + vipAmount.value;
});

/**
 * 处理支付方式确认
 * @param method 支付方式
 */
const handlePaymentConfirm = async (method: 'balance' | 'wechat') => {
  try {
    // 调用支付接口
    const payRes = await post("/pay/deposit", {
      amount: currentPaymentAmount.value,
      vipType: 1,
      deductionBalance: method === 'balance' ? 1 : 0, // 余额支付传1，微信支付传0
    });

    console.log("支付 payRes===>", payRes, method);

    if (payRes.code == 0) {
      if (method === 'wechat') {
        // 微信支付
        doPay(payRes.data);
      } else {
        // 余额支付
        if (payRes.data.code == 2) {
          // 余额支付成功
          Taro.showToast({
            title: "支付成功！",
            icon: "success",
            duration: 2000,
          });
          // 更新用户余额
          const newBalance = (userStore.userInfo.balance || 0) - parseFloat(currentPaymentAmount.value.toString());
          userStore.updateBalance(newBalance);
          
          setTimeout(() => {
            userStore.fetchUserInfo();
            Taro.navigateBack();
          }, 2000);
        } else {
          // 余额支付失败
          Taro.showToast({
            title: payRes.data.msg || "支付失败",
            icon: "error",
            duration: 2000,
          });
        }
      }
    } else {
      Taro.showToast({
        title: "支付失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error('支付失败:', error);
    Taro.showToast({
      title: "支付失败，请重试",
      icon: "none",
    });
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  showPaymentModal.value = false;
  Taro.showToast({
    title: "已取消支付",
    icon: "none",
  });
};

// 微信弹窗
const doPay = (param: any) => {
  (window as any).WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: param.appid, //公众号ID，由商户传入
      timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: param.nonceStr, //随机串
      package: param.prepayId,
      signType: "RSA", //微信签名方式：
      paySign: param.paySign, //微信签名
    },
    function (param: any) {
      if (param.err_msg == "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
        userStore.fetchUserInfo()
        Taro.showToast({
          title: "支付成功！",
          icon: "success",
          duration: 2000
        });
        
        setTimeout(() => {
          Taro.navigateBack();
        }, 2000);
      } else {
        userStore.fetchUserInfo()
        Taro.showToast({ title: "支付失败！", icon: "error", duration: 2000 });
      }
    }
  );
  // Taro.requestPayment({
  //   timeStamp: param.timeStamp,
  //   nonceStr: param.nonceStr,
  //   package: param.prepayId,
  //   signType: param.signType,
  //   paySign: param.paySign,
  //   success: function (res) {
  //     console.log("支付 success", res);
  //     Taro.showToast({
  //       title: "支付成功",
  //       icon: "success",
  //     });
  //     Taro.navigateBack();
  //     // txt.value = JSON.stringify(res)
  //   },
  //   fail: function (res) {
  //     console.log("支付 fail", res);
  //     Taro.showToast({
  //       title: "支付失败",
  //       icon: "error",
  //     });
  //     txt.value = JSON.stringify(res);
  //   },
  //   complete: function (res) {
  //     console.log("支付 complete", res);
  //   },
  // });
};


// 获取认证状态参数
const status = Taro.getCurrentInstance().router?.params.status || '';
const getAuthentication = async () => {
  if (status) {
    try {
      const res = await post("/user/getAuthentication");
      if (res.code == 0) {
        const data = res.data.columns;
        
        // 基础信息赋值
        formData.value.backPic = data.back_pic || ''; // 反面证件 -> 反面图片
        formData.value.frontPic = data.front_pic || ''; // 正面证件 -> 正面图片
        formData.value.id = data.id || 0; // id -> ID
        formData.value.realName = data.real_name || ''; // 用户名 -> 真实姓名
        formData.value.realNo = data.real_no || ''; // 证件编号 -> 身份证号
        formData.value.businessPic = data.business_pic || ''; // 营业执照 -> 营业执照图片
        formData.value.authorization = data.authorization || ''; // 授权书
        formData.value.is_pay = data.is_pay || 0; // 是否支付
        formData.value.type = data.type_merchant || 1; // 服务范围
        formData.value.serviceScope = data.service_scope || ''; // 服务范围
        
        // 根据是否有图片数据设置上传状态
        uploadedLicense.value = !!data.business_pic;
        uploadedBook.value = !!data.authorization;
        uploadedFrontCard.value = !!data.front_pic;
        uploadedBackCard.value = !!data.back_pic;

        
        // 调试图片路径
        console.log('图片路径调试:');
        console.log('营业执照:', data.business_pic, '状态:', uploadedLicense.value);
        console.log('授权书:', data.authorization, '状态:', uploadedBook.value);
        console.log('身份证正面:', data.front_pic, '状态:', uploadedFrontCard.value);
        console.log('身份证反面:', data.back_pic, '状态:', uploadedBackCard.value);
        console.log('完整图片路径:');
        console.log('营业执照完整路径:', getFullPath(data.business_pic || ''));
        console.log('授权书完整路径:', getFullPath(data.authorization || ''));
        console.log('身份证正面完整路径:', getFullPath(data.front_pic || ''));
        console.log('身份证反面完整路径:', getFullPath(data.back_pic || ''));
        
        // 服务范围处理 - 如果是字符串，转换为数组
        // if (data.service_scope) {
        //   if (typeof data.service_scope === 'string') {
        //     formData.value.service_scope = [data.service_scope];
        //   } else if (Array.isArray(data.service_scope)) {
        //     formData.value.service_scope = data.service_scope;
        //   } else {
        //     formData.value.service_scope = [];
        //   }
        // } else {
        //   formData.value.service_scope = [];
        // }
        
        // 行业处理 - 提取行业ID数组
        if (data.industrys && Array.isArray(data.industrys)) {
          const industryIds = data.industrys.map((item: any) => {
            if (item.columns && item.columns.industry_id) {
              return parseInt(item.columns.industry_id);
            }
            return null;
          }).filter((id: any) => id !== null);
          
          // 转换为字符串数组以匹配接口类型
          formData.value.industrys = industryIds.map((id: any) => id.toString());
          selectedIndustries.value = industryIds;
          
          // 更新行业显示文本
          if (industryIds.length > 0) {
            const industryNames = industryIds.map((id: any) => {
              const option = industryOptions.value.find((opt: any) => opt.value === id);
              return option ? option.text : '';
            }).filter((name: any) => name !== '');
            industryText.value = industryNames.join('、');
          }
        } else {
          formData.value.industrys = [];
          selectedIndustries.value = [];
          industryText.value = '';
        }
        
        // 商家类型处理
        const merchantType = data.type_merchant || '';
        formData.value.type = merchantType.toString();
        selectedType.value = merchantType.toString();
        
        // 更新商家类型显示
        if (merchantType && merchantTypes.value.length > 0) {
          const typeOption = merchantTypes.value.find(type => type.value === merchantType.toString());
          if (typeOption) {
            // 可以在这里更新UI显示
            console.log('当前商家类型:', typeOption.name);
          }
        }
        
        console.log('表单数据已更新:', formData.value);
        console.log('选中的行业:', selectedIndustries.value);
        console.log('选中的类型:', selectedType.value);
      } else {
        console.error('获取认证信息失败:', res.message);
        Taro.showToast({
          title: res.message || '获取认证信息失败',
          icon: 'error',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('获取认证信息异常:', error);
      Taro.showToast({
        title: '网络错误，请重试',
        icon: 'error',
        duration: 2000
      });
    }
  }
};

// 页面加载时获取认证信息
onMounted(() => {
  getAuthentication();
  selectType(selectedType.value);
});

</script>

<style lang="scss">
.bgs {
  .nut-cell-group__wrap {
    box-shadow: none !important;
  }
  .nut-textarea {
    padding: 0 !important;
  }
}

/* 授权书模版弹窗样式 */
.template-modal {
  background: white;
  border-radius: 24rpx;
  overflow: hidden;
  
  .modal-header {
    padding: 32rpx;
    text-align: center;
    border-bottom: 1rpx solid #f0f0f0;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-content {
    padding: 32rpx;
    
    .template-image {
      width: 100%;
      max-height: 600rpx;
      border-radius: 16rpx;
      margin-bottom: 32rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    }
    
    .modal-footer {
      text-align: center;
      
      .download-btn {
        background: #165DFF;
        border-radius: 20rpx;
        padding: 16rpx 48rpx;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }
}
</style>
